package gluehttp

import "strconv"

type PageRequest struct {
	PageNo    int    `form:"page_number,default=1" json:"page_number"`
	PageSize  int    `form:"page_size,default=20" json:"page_size"`
	SortField string `form:"sort_field" json:"sort_field"` // Sorted field name
	IsAsc     bool   `form:"is_asc" json:"is_asc"`         // Arrange in ascending order or not
}

func (p *PageRequest) Offset() int {
	if p.PageSize <= 0 {
		p.PageSize = 10
	}
	if p.PageNo <= 0 {
		p.PageNo = 1
	}
	return (p.PageNo - 1) * p.PageSize
}

type PageResponse struct {
	*PageRequest
	Total     int `json:"total"`      // Total Data Row
	PageTotal int `json:"page_total"` // PageCount
}

func (p *PageResponse) SetTotal(total int) {
	if p.PageSize <= 0 {
		p.PageSize = 10
	}
	if p.PageNo <= 0 {
		p.PageNo = 1
	}
	p.Total = total
	// Pages
	p.PageTotal = (total-1)/p.PageSize + 1
	//If the front page number is greater than the total page number of the database,
	//the maximum number of pages is used for database paging query
	if p.PageNo > p.PageTotal {
		p.PageNo = p.PageTotal
	}
}

func (p *PageResponse) SetPageRequest(pageNo string, pageSize string) {
	if pageNo != "" {
		p.PageNo, _ = strconv.Atoi(pageNo)
	}
	if pageSize != "" {
		p.PageSize, _ = strconv.Atoi(pageSize)
	}
}

func (p *PageResponse) SetPageResponse(total int, pageNo string, pageSize string) {
	p.SetPageRequest(pageNo, pageSize)
	p.SetTotal(total)
}
